package com.yuanfeng.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.activity.dto.*;
import com.yuanfeng.activity.entity.ActivityRedpacketBaseEntity;
import com.yuanfeng.activity.feign.UserServiceClient;
import com.yuanfeng.activity.mapper.ActivityRedpacketBaseMapper;
import com.yuanfeng.activity.mapper.ActivityRedpacketTemplateMapper;
import com.yuanfeng.activity.service.ActivityRedpacketBaseService;
import com.yuanfeng.activity.vo.AvaliableRpBaseResultVO;
import com.yuanfeng.activity.vo.CheckReceivedRpOrNotResultVO;
import com.yuanfeng.activity.vo.RedpacketDetailVO;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.exception.DefinedException;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.activity.RedTemplateEntityVO;
import com.yuanfeng.commoms.vo.activity.YfRedpacketBaseVO;
import com.yuanfeng.commoms.vo.activity.YfRedpacketTemplateVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ActivityRedpacketBaseServiceImpl
 * @Description 红包表
 * @Author cyp
 * @Date 2023-05-23 16:42:52
 * @Version 1.0
 **/
@Service
public class ActivityRedpacketBaseServiceImpl extends ServiceImpl<ActivityRedpacketBaseMapper, ActivityRedpacketBaseEntity>
        implements ActivityRedpacketBaseService {

    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private ActivityRedpacketTemplateMapper activityRedpacketTemplateMapper;

    @Override
    public ResponseResult checkReceivedRpOrNot(UserAvailableRedpacketQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        param.setRedpacketOwnerId(userInfo.getUserId());

        // 检验是否有未领取红包
        Integer count = this.baseMapper.checkReceivedRpOrNot(param);

        if (null == count) {
            return ResponseResult.fail(BizCodeEnume.NO_RED_ENVELOPES.getCode(), BizCodeEnume.NO_RED_ENVELOPES.getMsg());
        }

        return ResponseResult.success("有可领取红包");
    }

    @Override
    public ResponseResult insertAllAvaliable(Map<String, String> paraMap) {

        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        List<YfRedpacketTemplateVO> yfRedpacketTemplates = this.baseMapper.selectRedpacketTem(paraMap);
        Integer amount = 0;
        // 领取所有非新人红包
        for (YfRedpacketTemplateVO yfRedpacketTemplate : yfRedpacketTemplates) {
            // 查询红包是否领取过
            Map<String, String> checkMap = new HashMap<>();
            checkMap.put("redpacketOwnerId", userInfo.getUserId());
            checkMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId().toString());
            List<String> redpacketIdList = this.baseMapper.checkReceivedRedpacketOrNot(checkMap);
            // 如果未领取则可以领取
            if(CollectionUtils.isEmpty(redpacketIdList)){
                Map<String, Object> insertMap = new HashMap<>();
                insertMap.put("redpacketOwnerId", userInfo.getUserId());
                insertMap.put("redpacketOwnerName", userInfo.getUserName());
                insertMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId());
                insertMap.put("redpacketTitle", yfRedpacketTemplate.getRedpacketTTitle());
                insertMap.put("redpacketDesc", yfRedpacketTemplate.getRedpacketTDesc());
                insertMap.put("redpacketStartDate", yfRedpacketTemplate.getRedpacketTStartDate());
                insertMap.put("redpacketEndDate", yfRedpacketTemplate.getRedpacketTEndDate());
                insertMap.put("redpacketPrice", yfRedpacketTemplate.getRedpacketTPrice());
                insertMap.put("shopLimit", yfRedpacketTemplate.getShopLimit());
                insertMap.put("goodsCatLimit", yfRedpacketTemplate.getGoodsCatLimit());
                insertMap.put("redpacketTOrderlimit", yfRedpacketTemplate.getRedpacketTOrderlimit());
                insertMap.put("redpacketFrom", 1);
                Integer torf = this.baseMapper.insertyfRedpacketBase(insertMap);
                amount = amount + torf;
                // 增加红包领取数量
                Map<String, String> updateMap = new HashMap<String, String>();
                updateMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId().toString());
                this.baseMapper.updateRedpGiveout(updateMap);
            }
        }
        // 新人则继续领取
        if ("1".equals(userInfo.getUserIsNew())) {
            List<YfRedpacketTemplateVO> newRedpacketTems = this.baseMapper.selectNewRedpacketTem(paraMap);
            for (YfRedpacketTemplateVO yfRedpacketTemplate : newRedpacketTems) {
                Map<String, Object> insertMap = new HashMap<String, Object>();
                insertMap.put("redpacketOwnerId", userInfo.getUserId());
                insertMap.put("redpacketOwnerName", userInfo.getUserName());
                insertMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId());
                insertMap.put("redpacketTitle", yfRedpacketTemplate.getRedpacketTTitle());
                insertMap.put("redpacketDesc", yfRedpacketTemplate.getRedpacketTDesc());
                insertMap.put("redpacketStartDate", yfRedpacketTemplate.getRedpacketTStartDate());
                insertMap.put("redpacketEndDate", yfRedpacketTemplate.getRedpacketTEndDate());
                insertMap.put("redpacketPrice", yfRedpacketTemplate.getRedpacketTPrice());
                insertMap.put("shopLimit", yfRedpacketTemplate.getShopLimit());
                insertMap.put("goodsCatLimit", yfRedpacketTemplate.getGoodsCatLimit());
                insertMap.put("redpacketTOrderlimit", yfRedpacketTemplate.getRedpacketTOrderlimit());
                insertMap.put("redpacketFrom", 1);
                Integer torf = this.baseMapper.insertyfRedpacketBase(insertMap);
                amount = amount + torf;
                // 增加红包已领取数量
                Map<String, String> updateMap = new HashMap<String, String>();
                updateMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId().toString());
                this.baseMapper.updateRedpGiveout(updateMap);
            }

            if (!CollectionUtils.isEmpty(newRedpacketTems)) {
                // 更新是否是新人
                userServiceClient.updateIsNew(paraMap);
            }

        }
        return ResponseResult.success(amount);
    }

    @Override
    public YfRedpacketBaseVO getRedDetail(Map<String, String> paraMap) {
        YfRedpacketBaseVO redpDetail = this.baseMapper.getRedDetail(paraMap);
        return redpDetail;
    }

    @Override
    public ResponseResult selectMyRedPacket(UserAvailableRedpacketDTO param) {
        String userString = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.getToken());
        if (userString == null || "".equals(userString)) {
            throw new DefinedException(BizCodeEnume.TOKEN_IS_INVALID.getCode(), BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }

        // 获取用户信息
        UserInfoDTO dto = JSON.parseObject(userString, UserInfoDTO.class);
        param.setRedpacketOwnerId(dto.getUser().getUserId());
        // (1-未用,2-已用,3-过期))
        Integer redpacketTState = param.getRedpacketState();

        param.setRedpacketState(redpacketTState);
        //分页
        //将对象转换为map
        Map data = null;
        try {
            data = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        //分页查询数据
        IPage<ActivityRedpacketBaseEntity> page = this.baseMapper.queryBrandList(new Query<ActivityRedpacketBaseEntity>().getPage(data),param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public List<YfRedpacketTemplateVO> selectRedPacket(List<Integer> id) {
        List<YfRedpacketTemplateVO> redpDetail = this.baseMapper.selectRedPacket(id);
        return redpDetail;
    }

    @Override
    public ResponseResult insertRedPacket(Map<String, Object> insertMap) {
        this.baseMapper.insertRedPacket(insertMap);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateRedpGiveout(Map<String, String> updateMap) {
        this.baseMapper.updateRedpGiveout(updateMap);
        return ResponseResult.success();
    }

    @Override
    public List<RedTemplateEntityVO> selectredtemplateId(List<Integer> redIdList) {
        return this.baseMapper.selectredtemplateId(redIdList);
    }

    @Override
    public Integer selectuserred(List<Integer> redIdList, String userId) {
        return this.baseMapper.selectuserred(redIdList,userId);
    }

    @Override
    public ResponseResult insertRedpacketBase(Map<String, Object> paraMap) {
        Integer result=this.baseMapper.insertRedpacketBase(paraMap);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult userList(Map<String, Object> paraMap) {
        IPage<ActivityRedpacketBaseEntity> page=this.page(new Query<ActivityRedpacketBaseEntity>().getPage(paraMap),
                new LambdaQueryWrapper<ActivityRedpacketBaseEntity>()
                                                .eq(ActivityRedpacketBaseEntity::getRedpacketTId, Integer.valueOf(paraMap.get("redpacketTId").toString()))
                                                .orderByDesc(ActivityRedpacketBaseEntity::getRedpacketActiveDate));

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult DetaillistExp(Map<String, Object> param, HttpServletResponse response) throws IOException {
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        String finishTime = dateformat.format(new Date());

        List<Map<String, String>> dataset = Lists.newArrayList();

        boolean flag=param.containsKey("redpacketOwnerName");
        if(flag){
            flag=StringUtils.isNotEmpty(param.get("redpacketOwnerName").toString());
        }
        List<ActivityRedpacketBaseEntity> detail =this.baseMapper.selectList(new LambdaQueryWrapper<ActivityRedpacketBaseEntity>()
                .eq(param.containsKey("redpacketTId")&&param.get("redpacketTId")!="",ActivityRedpacketBaseEntity::getRedpacketTId,param.get("redpacketTId").toString())
                .le(param.containsKey("finishTime"),ActivityRedpacketBaseEntity::getRedpacketEndDate,param.containsKey("finishTime")?param.get("finishTime").toString():null)
                .ge(param.containsKey("startTime"),ActivityRedpacketBaseEntity::getRedpacketEndDate,param.containsKey("startTime")?param.get("startTime").toString():null)
                .like(flag,ActivityRedpacketBaseEntity::getRedpacketOwnerName,flag?param.get("redpacketOwnerName").toString():null)
                .eq(param.containsKey("redpacketState"),ActivityRedpacketBaseEntity::getRedpacketState,param.containsKey("redpacketState")?param.get("redpacketState").toString():null));
        for (ActivityRedpacketBaseEntity res : detail) {
            HashMap<String, String> map = Maps.newHashMap();

            if (res.getRedpacketState() != null) {
                switch (res.getRedpacketState()) {
                    case 1:
                        map.put("红包状态","未使用");
                        break;
                    case 2:
                        map.put("红包状态","已使用");
                        break;
                    case 3:
                        map.put("红包状态","已过期");
                        break;
                }

            }
            map.put("红包标题",res.getRedpacketTitle());
            map.put("红包描述",res.getRedpacketDesc());
            map.put("红包有效期开始时间",DateUtils.format(res.getRedpacketStartDate(),"yyyy-MM-dd HH:mm:ss"));
            map.put("红包有效期结束时间",DateUtils.format(res.getRedpacketEndDate(),"yyyy-MM-dd HH:mm:ss"));
            map.put("红包面额",res.getRedpacketPrice().toString());
            map.put("订单编号",res.getRedpacketOrderId());
            map.put("所有者名称",res.getRedpacketOwnerName());
            map.put("红包领取时间",DateUtils.format(res.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            dataset.add(map);
        }
        String[] headers = {"红包标题","红包描述","红包有效期开始时间","红包有效期结束时间","红包面额","红包状态","订单编号","所有者名称","红包领取时间"};
// excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("红包使用详情", dataset);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult listRedpacketDetailTemp(Map<String, Object> param) {
        if (RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + param.get("token"))) {

            IPage<RedpacketDetailVO> page=this.baseMapper.querylistRedpacketDetailTemp(new Query<RedpacketDetailVO>().getPage(param),
                    param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {

            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }


    }

    @Override
    public ResponseResult queryList(UserAvailableRedpacketQueryDTO param) {
        Integer goodsId = param.getGoodsId();

        List<YfRedpacketTemplateVO> newRpList = Lists.newArrayList();
        Integer receiveOrNot = 0;
        boolean flag = false;

        String token = param.getToken();
        // 获取用户信息
        UserInfoVO userInfo = null;

        if (StringUtils.isNotBlank(token)) {
            userInfo = ParseTokenUtils.getUserInfoByToken(token);
            param.setRedpacketOwnerId(userInfo.getUserId());
        }

        List<CheckReceivedRpOrNotResultVO> receivedRpList = this.baseMapper.checkReceivedRpOrNot2(param);

        List<YfRedpacketTemplateVO> yfRedpacketTemplates = this.baseMapper.selectRedpacketTemList(param);
        for (YfRedpacketTemplateVO yfRedpacketTemplate : yfRedpacketTemplates) {


            Integer redpacketTType = yfRedpacketTemplate.getRedpacketTType();

            if (StringUtils.isNotBlank(token)) {

                // 判断是否
                for (CheckReceivedRpOrNotResultVO receivedRp : receivedRpList) {
                    Integer redpacketState = receivedRp.getRedpacketState();

                    if (yfRedpacketTemplate.getRedpacketTId().intValue() == receivedRp.getRedpacketTId().intValue()) {

                        // 判断是否是新人红包，如果是则根据userIsNew判断是否是新人
                        if (yfRedpacketTemplate.getRedpacketTType().equals(CommonType.redpacketTType.NEW_PERSON_REGISTRATION
                                .getCode())
                                || yfRedpacketTemplate.getRedpacketTType().equals(CommonType.redpacketTType.MULTI_PRODUCT_NEWCOMERS
                                .getCode())) {
                            // 0未领取1已领取2新人专享3已用4过期
                            if ("0".equals(userInfo.getUserIsNew())) {
                                // 不是新用户则不可以领取
                                if (null == redpacketState || redpacketState.intValue() == 1) {
                                    receiveOrNot = CommonType.PromotionReceiveOrNot.IMMEDIATELY.getCode();
                                } else if (redpacketState.intValue() == 2) {
                                    receiveOrNot = CommonType.PromotionReceiveOrNot.ALREADY_USE.getCode();
                                } else if (redpacketState.intValue() == 3) {
                                    receiveOrNot = CommonType.PromotionReceiveOrNot.EXPIRE.getCode();
                                } else {
                                    receiveOrNot = CommonType.PromotionReceiveOrNot.NEW_VIP.getCode();
                                }
                            } else {
                                receiveOrNot = CommonType.PromotionReceiveOrNot.NO_RECEIVE.getCode();
                            }

                        } else {
                            // 如果未领取则可以领取 红包状态(1-未用,2-已用,3-过期
                            // ReceiveOrNot:0未领取1立即使用2不可领取3已用4过期
                            if (null == redpacketState) {
                                receiveOrNot = CommonType.PromotionReceiveOrNot.NO_RECEIVE.getCode();
                            } else if (redpacketState.intValue() == 2) {

                                receiveOrNot = CommonType.PromotionReceiveOrNot.ALREADY_USE.getCode();
                            } else if (redpacketState.intValue() == 3) {
                                receiveOrNot = CommonType.PromotionReceiveOrNot.EXPIRE.getCode();
                            } else {
                                receiveOrNot = CommonType.PromotionReceiveOrNot.IMMEDIATELY.getCode();
                            }

                        }
                        yfRedpacketTemplate.setReceiveOrNot(receiveOrNot);
                        flag = true;
                        break;
                    }

                }

            } else {
                flag = true;
            }

            if (CommonType.redpacketTType.NEW_PERSON_REGISTRATION.getCode().equals(redpacketTType)
                    || CommonType.redpacketTType.ORDINARY.getCode().equals(redpacketTType)
                    || CommonType.redpacketTType.EXCLUSIVE.getCode().equals(redpacketTType)) {
                flag = true;
            } else {

                // 多品红包类型：1多品配置2专区
                Integer manyRedpacketType = yfRedpacketTemplate.getManyRedpacketType();

                if (manyRedpacketType.equals(1)) {
                    String goodsCatLimit = yfRedpacketTemplate.getGoodsCatLimit();
                    if (StringUtils.isNotEmpty(goodsCatLimit)) {
                        List<Integer> goodsCatLimitList = Arrays
                                .asList((Integer[]) ConvertUtils.convert(goodsCatLimit.split(","), Integer.class));

                        if (goodsCatLimitList.contains(goodsId)) {
                            flag = true;
                        } else {
                            flag = false;
                        }
                    }
                } else {
                   flag = false;
                }

            }

            if (flag) {
                newRpList.add(yfRedpacketTemplate);
            }

        }
        return ResponseResult.success(newRpList);

    }

    @Override
    public ResponseResult receive(Map<String, String> paraMap) {
        ResponseResult result = new ResponseResult();
        // 获取jedis实例
        Jedis jedis = RedisUtil.getJedis();
        RedisLock redisLock = null;
        try {

            UserInfoVO userInfo =  ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));

            String redpacketOwnerId = userInfo.getUserId().toString();
            String redpacketTId = paraMap.get("redpacketTId");

            redisLock = new RedisLock(jedis, "user-rp-" + redpacketOwnerId + redpacketTId, 10000);
            // 用户锁
            if (redisLock.lock()) {
                result = this.insertRpBase(paraMap, userInfo);
            } else {

                String macAddress = paraMap.get("macAddress");

                if (null != macAddress) {
                    String voucherId2 =  this.baseMapper.checkReceivedRpOrNot3(paraMap);

                    if (null != voucherId2) {
                        return ResponseResult.fail(0, "同一部手机只能领取一次该红包哦");
                    }
                }
                return ResponseResult.fail(0, "红包领取失败");
            }

            return result;
        } catch (InterruptedException e) {
            return ResponseResult.fail(0, "红包领取失败");
        } finally {

            jedis.close();
        }
    }
    @Transactional
    public ResponseResult insertRpBase(Map<String, String> paraMap, UserInfoVO userInfo) {

        // 判断红包是否领取过
        Map<String, String> checkMap = new HashMap<String, String>();
        String redpacketOwnerId = userInfo.getUserId().toString();
        String redpacketTId = paraMap.get("redpacketTId");

        checkMap.put("redpacketOwnerId", redpacketOwnerId);
        checkMap.put("redpacketTId", redpacketTId);

        String macAddress = paraMap.get("macAddress");
        //查询该红包领取限制
        Integer redlimit = activityRedpacketTemplateMapper.checkReceivedRp(checkMap);

        //判断红包是否到达领取限制
        Integer voucherId = this.baseMapper.checkReceivedRpOrNot1(checkMap);
        if (voucherId >= redlimit && redlimit != 0) {
            return ResponseResult.fail(0, "红包已到达领取上限");
        }

        if (null != macAddress) {
            String voucherId2 = this.baseMapper.checkReceivedRpOrNot3(paraMap);

            if (null != voucherId2) {
                return ResponseResult.fail(0, "同一部手机只能领取一次该红包哦");
            }
        }

        YfRedpacketTemplateVO yfRedpacketTemplate = activityRedpacketTemplateMapper.selectRpTemById(paraMap);

        if (yfRedpacketTemplate.getRedpacketIsBooking().intValue() == 2
                && !DateUtils.compareDate(yfRedpacketTemplate.getRobRedpacketStartDate(),
                yfRedpacketTemplate.getRobRedpacketEndDate())) {
            return ResponseResult.fail(0, "活动未开始，敬请期待！");
        }

        if (yfRedpacketTemplate.getRedpacketTGiveout() >= yfRedpacketTemplate.getRedpacketTTotal()) {
            return ResponseResult.fail(0, "红包已领完");
        }

        if (userInfo.getUserIsNew().equals("1") && (yfRedpacketTemplate.getRedpacketTType().equals(1)
                || yfRedpacketTemplate.getRedpacketTType().equals(5))) {
            List<YfRedpacketTemplateVO> newRedpacketTems = this.baseMapper.selectNewRedpacketTem(paraMap);

            if (CollectionUtils.isEmpty(newRedpacketTems)) {
                return ResponseResult.fail(0, "没有新人红包");
            }

            for (YfRedpacketTemplateVO newRedpacketTem : newRedpacketTems) {

                if (yfRedpacketTemplate.getRedpacketTGiveout() < yfRedpacketTemplate.getRedpacketTTotal()) {
                    Map<String, Object> insertMap = new HashMap<String, Object>();
                    insertMap.put("redpacketOwnerId", userInfo.getUserId());
                    insertMap.put("redpacketOwnerName", userInfo.getUserName());
                    insertMap.put("redpacketTId", newRedpacketTem.getRedpacketTId());
                    insertMap.put("redpacketTitle", newRedpacketTem.getRedpacketTTitle());
                    insertMap.put("redpacketDesc", newRedpacketTem.getRedpacketTDesc());
                    insertMap.put("redpacketStartDate", newRedpacketTem.getRedpacketTStartDate());
                    insertMap.put("redpacketEndDate", newRedpacketTem.getRedpacketTEndDate());
                    insertMap.put("redpacketPrice", newRedpacketTem.getRedpacketTPrice());
                    insertMap.put("shopLimit", newRedpacketTem.getShopLimit());
                    insertMap.put("goodsCatLimit", newRedpacketTem.getGoodsCatLimit());
                    insertMap.put("redpacketTOrderlimit", newRedpacketTem.getRedpacketTOrderlimit());
                    insertMap.put("macAddress", macAddress);
                    this.baseMapper.insertRedpacketBase(insertMap);

                    // 增加红包已领取数量
                    Map<String, String> updateMap = new HashMap<String, String>();
                    updateMap.put("redpacketTId", newRedpacketTem.getRedpacketTId().toString());
                    this.baseMapper.updateRedpGiveout(updateMap);
                }

            }

            try {
                if (!CollectionUtils.isEmpty(newRedpacketTems)) {
                    // 更新是否是新人
                    this.baseMapper.updateIsNew(paraMap);
                }
            } catch (Exception e) {
            }

            return ResponseResult.success("红包领取成功");
        }

        // 红包类型，1-新人注册红包，2-普通红包，3-单品红包 4-店铺红包
        // ,5-单品新人红包 默认2
        if (yfRedpacketTemplate.getRedpacketTType().intValue() == 1
                || yfRedpacketTemplate.getRedpacketTType().intValue() == 5) {
            return ResponseResult.fail(0, "领取失败，新人专享");
        }
        Map<String, Object> insertMap = new HashMap<String, Object>();

        insertMap.put("redpacketOwnerId", userInfo.getUserId());
        insertMap.put("redpacketOwnerName", userInfo.getUserName());
        insertMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId());
        insertMap.put("redpacketTitle", yfRedpacketTemplate.getRedpacketTTitle());
        insertMap.put("redpacketDesc", yfRedpacketTemplate.getRedpacketTDesc());
        insertMap.put("redpacketStartDate", yfRedpacketTemplate.getRedpacketTStartDate());
        insertMap.put("redpacketEndDate", yfRedpacketTemplate.getRedpacketTEndDate());
        insertMap.put("redpacketPrice", yfRedpacketTemplate.getRedpacketTPrice());
        insertMap.put("shopLimit", yfRedpacketTemplate.getShopLimit());
        insertMap.put("goodsCatLimit", yfRedpacketTemplate.getGoodsCatLimit());
        insertMap.put("redpacketTOrderlimit", yfRedpacketTemplate.getRedpacketTOrderlimit());
        insertMap.put("macAddress", macAddress);

        Integer torf =  this.baseMapper.insertyfRedpacketBase(insertMap);
        // 增加红包领取数量
        Map<String, String> updateMap = new HashMap<String, String>();
        updateMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId().toString());
        this.baseMapper.updateRedpGiveout(updateMap);

        if (0 == torf) {
            return ResponseResult.fail(0, "插入红包失败");
        }
        return ResponseResult.success("红包领取成功");
    }

    public Integer insertSpinwinRpBase(Map<String, String> paraMap, UserInfoVO userInfo) {

        // 判断红包是否领取过
        Map<String, String> checkMap = new HashMap<String, String>();
        String redpacketOwnerId = userInfo.getUserId().toString();
        String redpacketTId = paraMap.get("redpacketTId");

        checkMap.put("redpacketOwnerId", redpacketOwnerId);
        checkMap.put("redpacketTId", redpacketTId);

        YfRedpacketTemplateVO yfRedpacketTemplate = activityRedpacketTemplateMapper.selectRpTemById(paraMap);

        Map<String, Object> insertMap = new HashMap<String, Object>();
        insertMap.put("redpacketId", "");

        insertMap.put("redpacketOwnerId", userInfo.getUserId());
        insertMap.put("redpacketOwnerName", userInfo.getUserName());
        insertMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId());
        insertMap.put("redpacketTitle", yfRedpacketTemplate.getRedpacketTTitle());
        insertMap.put("redpacketDesc", yfRedpacketTemplate.getRedpacketTDesc());
        insertMap.put("redpacketStartDate", yfRedpacketTemplate.getRedpacketTStartDate());
        insertMap.put("redpacketEndDate", yfRedpacketTemplate.getRedpacketTEndDate());
        insertMap.put("redpacketPrice", yfRedpacketTemplate.getRedpacketTPrice());
        insertMap.put("shopLimit", yfRedpacketTemplate.getShopLimit());
        insertMap.put("goodsCatLimit", yfRedpacketTemplate.getGoodsCatLimit());
        insertMap.put("redpacketTOrderlimit", yfRedpacketTemplate.getRedpacketTOrderlimit());
        insertMap.put("macAddress", "");

        this.baseMapper.insertyfRedpacketBase(insertMap);
        Integer redpacketId = Integer.parseInt(insertMap.get("redpacketId").toString());

        // 增加红包领取数量
        Map<String, String> updateMap = new HashMap<String, String>();
        updateMap.put("redpacketTId", yfRedpacketTemplate.getRedpacketTId().toString());
        this.baseMapper.updateRedpGiveout(updateMap);

        return redpacketId;
    }

    @Override
    public ResponseResult selectByDeposit(GetAvaliableRedpDTO param) {

        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String userId = userInfo.getUserId();

        List<GetShopInfoDTO> getShopInfos = param.getShopList();

        Double totalPrice = param.getTotalPrice();
        List<AvaliableRpGoodsListDTO> allGoodsList = Lists.newArrayList();



        // redpacketTType; 红包类型，1-新人注册红包，2-普通红包，3-单品红包 4-店铺红包
        // 5-单品新人红包 6-赠送红包 默认2
        List<AvaliableRpBaseResultVO> avaliableRpList = Lists.newArrayList();

        // 查询普通红包
        List<AvaliableRpBaseResultVO> generalRbList = this.baseMapper.selectUserAvaliableRpList(userId, 2,
                param.getPlatForm());
        avaliableRpList = getAvaliableRp(totalPrice, avaliableRpList, generalRbList);

        // 查询赠送红包
        List<AvaliableRpBaseResultVO> sendUserRbList = this.baseMapper.selectUserAvaliableRpList(userId, 6,
                param.getPlatForm());
        avaliableRpList = getAvaliableRp(totalPrice, avaliableRpList, sendUserRbList);

        // 查询新人红包
        List<AvaliableRpBaseResultVO> newPersonRbList = this.baseMapper.selectUserAvaliableRpList(userId, 1,
                param.getPlatForm());

        avaliableRpList = getAvaliableRp(totalPrice, avaliableRpList, newPersonRbList);

        //查询plus红包
        List<AvaliableRpBaseResultVO> plusRbList = this.baseMapper.selectUserAvaliableRpList(userId, 7,
                param.getPlatForm());
        avaliableRpList = getAvaliableRp(totalPrice, avaliableRpList, plusRbList);

        return ResponseResult.success(avaliableRpList);
    }

    private List<AvaliableRpBaseResultVO> getAvaliableRp(Double totalPrice, List<AvaliableRpBaseResultVO> avaliableRpList,
                                                       List<AvaliableRpBaseResultVO> newPersonRbList) {
        if (!CollectionUtils.isEmpty(newPersonRbList)) {
            for (AvaliableRpBaseResultVO newPersonRb : newPersonRbList) {
                if(totalPrice==null){
                    totalPrice=0.0;
                }
                if (totalPrice >= newPersonRb.getRedpacketTOrderlimit()) {
                    avaliableRpList.add(newPersonRb);
                }
            }
        }
        return avaliableRpList;
    }
}

